package com.jiawa.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.domain.Content;
import com.jiawa.wiki.domain.Doc;
import com.jiawa.wiki.domain.DocExample;
import com.jiawa.wiki.exception.BusinessException;
import com.jiawa.wiki.exception.BusinessExceptionCode;
import com.jiawa.wiki.mapper.ContentMapper;
import com.jiawa.wiki.mapper.DocMapper;
import com.jiawa.wiki.req.DocQueryReq;
import com.jiawa.wiki.req.DocSaveReq;
import com.jiawa.wiki.resp.DocQueryResp;
import com.jiawa.wiki.resp.PageResp;
import com.jiawa.wiki.util.CopyUtil;
import com.jiawa.wiki.util.RedisUtil;
import com.jiawa.wiki.util.RequestContext;
import com.jiawa.wiki.util.SnowFlake;
import com.jiawa.wiki.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 荀彧 2021/5/17
 * 文档 service
 */
@Service
@Slf4j
public class DocService {

    @Resource
    private DocMapper mapper;

    @Resource
    private ContentMapper contentMapper;

    @Resource
    private SnowFlake snowFlake;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private WsService wsService;

    /**
     * 查询docs
     *
     * @param req
     * @return
     */
    public PageResp<DocQueryResp> list(DocQueryReq req) {
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        // 分页
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Doc> docs = mapper.selectByExample(docExample);
        PageInfo<Doc> info = new PageInfo<>(docs);
        log.info("总条数:{}", info.getTotal());
        log.info("总页数:{}", info.getPageNum());
        PageResp<DocQueryResp> resp = new PageResp<>();
        resp.setTotal(info.getTotal());
        resp.setList(CopyUtil.copyList(docs, DocQueryResp.class));
        return resp;
    }

    @Transactional
    public void save(DocSaveReq saveReq) {
        Doc doc = CopyUtil.copy(saveReq, Doc.class);
        Content content = CopyUtil.copy(saveReq, Content.class);
        if (ObjectUtils.isEmpty(saveReq.getId())) {
            doc.setId(snowFlake.nextId());
            content.setId(doc.getId());
            doc.setViewCount(0);
            doc.setVoteCount(0);
            mapper.insert(doc);
            contentMapper.insert(content);
        } else {
            mapper.updateByPrimaryKey(doc);
            int count = contentMapper.updateByPrimaryKeyWithBLOBs(content);
            if (count == 0) {
                contentMapper.insert(content);
            }
        }
    }

    /**
     * 删除操作
     *
     * @param ids
     */
    public void delete(List<String> ids) {
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        criteria.andIdIn(ids);
        mapper.deleteByExample(docExample);
    }

    /**
     * 展示所有
     *
     * @param
     * @return
     */
    public PageResp<DocQueryResp> all(Long ebookId) {
        DocExample docExample = new DocExample();
        docExample.createCriteria().andEbookIdEqualTo(ebookId);
        docExample.setOrderByClause("sort asc");
        List<Doc> docs = mapper.selectByExample(docExample);
        PageResp<DocQueryResp> resp = new PageResp<>();
        resp.setTotal(docs.size());
        resp.setList(CopyUtil.copyList(docs, DocQueryResp.class));
        return resp;
    }

    public String findContent(Long id) {
        Content content = contentMapper.selectByPrimaryKey(id);
        // 文档阅读数+1
        mapper.increaseViewCount(id);
        if (ObjectUtils.isEmpty(content)) {
            return "";
        } else {
            return content.getContent();
        }
    }


    /**
     * 点赞
     */
    public void vote(Long id) {
        // docMapperCust.increaseVoteCount(id);
        // 远程IP+doc.id作为key，24小时内不能重复
        String ip = RequestContext.getRemoteAddr();
        if (redisUtil.validateRepeat("DOC_VOTE_" + id + "_" + ip, 5000)) {
            mapper.increaseVoteCount(id);
            Doc docDb = mapper.selectByPrimaryKey(id);
            String logId = MDC.get("LOG_ID");
            String info = docDb.getName() + "被点赞了！";
            wsService.sendInfo(info, logId);

        } else {
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }
    }

    public void updateEbookInfo() {
        mapper.updateEbookInfo();
    }
}

